package com.aiss.ws.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiss.ws.Entity.AnswerItem;
import com.aiss.ws.Entity.ExamItem;
import com.aiss.ws.Entity.TestItem;
import com.aiss.ws.R;
import com.aiss.ws.adapter.AnswerAdatper;
import com.aiss.ws.httptools.GetJSONObjectPostUtil;
import com.aiss.ws.httptools.GetJsonListener;
import com.aiss.ws.utils.Command;
import com.aiss.ws.utils.CommonUtils;
import com.aiss.ws.utils.Futil;
import com.aiss.ws.utils.SetViewHeight;
import com.aiss.ws.utils.Url;
import com.aiss.ws.widget.MyListView;
import com.lidroid.xutils.exception.HttpException;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by chenqiang
 */
@EActivity(R.layout.activity_answer)
public class AnswerActivity extends BaseActivity {

    private ExamItem item = new ExamItem();

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(msg.what==Command.HANDLECODE11){



                try {
                    JSONObject obj = (JSONObject) msg.obj;


                    JSONObject object = obj.getJSONObject("return_data");
                    item.setCourse_idx(object.getString("course_idx"));
                    item.setRemaining_time(object.getString("remaining_time"));
                    item.setEnd_time(object.getString("end_time"));
                    item.setStatus_descri(object.getString("status_descri"));

                    if(is_true!=1&&type==Command.SUITE[1]){
                        item.setExam_time(object.getString("exam_time"));
                    }

                    JSONArray array = object.getJSONArray("test_list");
                    List<TestItem> testItems = new ArrayList<>();
                    for(int i = 0 ; i < array.length();i++){
                        TestItem testItem = new TestItem();
                        testItem.setIdx(array.getJSONObject(i).getString("idx"));
                        testItem.setIs_label(array.getJSONObject(i).getString("is_label"));
                        testItem.setBook_page(array.getJSONObject(i).getString("book_page"));
                        testItem.setAnswer(array.getJSONObject(i).getString("answer"));
                        testItem.setComplexity(array.getJSONObject(i).getString("complexity"));
                        testItem.setExplain(array.getJSONObject(i).getString("explain"));
                        testItem.setNamex(array.getJSONObject(i).getString("namex"));
                        testItem.setType(array.getJSONObject(i).getString("type"));
                        testItem.setTitle(array.getJSONObject(i).getString("title"));
                        JSONArray array2 = array.getJSONObject(i).getJSONArray("options");

                        List<AnswerItem> answerItems = new ArrayList<>();
                        for(int j = 0 ; j < array2.length();j++){
                            AnswerItem answerItem = new AnswerItem();
                            answerItem.setKey(array2.getJSONObject(j).getString("key"));
                            answerItem.setValue(array2.getJSONObject(j).getString("value"));
                            answerItems.add(answerItem);
                        }

                        testItem.setAnswerItems(answerItems);
                        testItems.add(testItem);
                    }
                    item.setTestItems(testItems);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //分隔时分秒
                String times [] = item.getRemaining_time().split(",");
                hour = Integer.parseInt(times[0]);
                min = Integer.parseInt(times[1]);
                sec = Integer.parseInt(times[2]);

                if(is_true!=1&&type==Command.SUITE[1]){
                    //分隔考试时分秒
                    String times2 [] = item.getExam_time().split(",");
                    hour2 = Integer.parseInt(times2[0]);
                    min2 = Integer.parseInt(times2[1]);
                    sec2 = Integer.parseInt(times2[2]);
                }


                setGrading();
                setAdatper();
                if(is_true==1){
                    time_ll.setVisibility(View.INVISIBLE);
                }else{
                    setTime();
                }

                hideLoading();
                rel_content.setVisibility(View.VISIBLE);

            }else if(msg.what==Command.HANDLECODE12){//标记成功
                item.getTestItems().get(position).setIs_label("1");
                label_img_press.setVisibility(View.VISIBLE);
                label_img.setVisibility(View.GONE);
                label_tv.setTextColor(getResources().getColor(R.color.app));

            }else if(msg.what== Command.HANDLECODE13){//标记失败
                item.getTestItems().get(position).setIs_label("0");
                label_img_press.setVisibility(View.GONE);
                label_img.setVisibility(View.VISIBLE);
                label_tv.setTextColor(getResources().getColor(R.color.content));
            }else if(msg.what==1000){

                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        try {
                            Thread.sleep(1500);
                            getfinish();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }.start();
                return ;
            }


        }
    };

    @ViewById(R.id.title)
    TextView title_tv;


    /**
     * 时间布局
     */
    @ViewById(R.id.time_ll)
    LinearLayout time_ll;

    @ViewById(R.id.rel_content)
    RelativeLayout rel_content;

    private int time = 0;
    //控制时间和接口
    private boolean flag = true;

    private int hour;//时
    private int min;//分
    private int sec;//秒

    private String hour_str;
    private String min_str;
    private String sec_str;

    private int hour2;//时
    private int min2;//分
    private int sec2;//秒

    private String hour_str2;
    private String min_str2;
    private String sec_str2;








    /**
     * 当前批阅的状态
     */
    @UiThread
    void setGrading(){
        if(type==Command.SUITE[1]){//当前为测试的状态
            grading_tv_tv.setText("交卷");
            commit_time_ll.setVisibility(View.VISIBLE);
        }else{//当前为联系、标注或错题的状态
            grading_tv_tv.setText("批阅");
            commit_time_ll.setVisibility(View.GONE);

        }
    }


    /**
     * 时间倒计时
     */
    @UiThread
    void setTime(){
        new Thread(){
            @Override
            public void run() {
                super.run();

                while(flag){
                    try {
                        Thread.sleep(1000);
                        ++time;
                        if(time%180==0){
                            sendTime();
                        }

                        if(sec!=0){
                            --sec;


                        }else{

                            if(min!=0){
                                --min;
                                sec+=59;
                            }else{

                                if(hour!=0){
                                    --hour;
                                    min+=59;
                                    sec+=59;
                                }else{
                                    flag = false;
                                    showMessage("该题已到期，2秒后将自动退出");
                                    new Thread(){
                                        @Override
                                        public void run() {
                                            super.run();
                                            try {
                                                Thread.sleep(2000);
                                                getfinish();
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }

                                        }
                                    }.start();
                                }

                            }

                        }

                        setText();
                        //测试时间线程
                        if(is_true!=1&&type==Command.SUITE[1]){
                            if(sec2!=0){
                                --sec2;


                            }else{

                                if(min2!=0){
                                    --min2;
                                    sec2+=59;
                                }else{

                                    if(hour2!=0){
                                        --hour2;
                                        min2+=59;
                                        sec2+=59;
                                    }else{
                                        flag = false;
                                        showMessage("答题时间到，5秒后将自动交卷");
                                        new Thread(){
                                            @Override
                                            public void run() {
                                                super.run();
                                                try {
                                                    Thread.sleep(5000);
                                                    jiaojuan();
                                                } catch (InterruptedException e) {
                                                    e.printStackTrace();
                                                }

                                            }
                                        }.start();
                                    }

                                }

                            }
                            setText2();
                        }



                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }



            }
        }.start();
    }

    /**
     * 测试时间
     */
    @ViewById(R.id.time_tv)
    TextView time_tv;

    @ViewById(R.id.time_tv2)
    TextView time_tv2;


    /**
     * 时间显示
     */
    @UiThread
    void setText(){
        if(hour>=0&&hour<=9){
            hour_str = "0"+hour;
        }else{
            hour_str = ""+hour;
        }

        if(min>=0&&min<=9){
            min_str = "0" + min;
        }else{
            min_str = min+"";
        }

        if(sec>=0&&sec<=9){
            sec_str = "0"+sec;
        }else{
            sec_str = sec+"";
        }

        time_tv.setText(hour_str+":"+min_str+":"+sec_str);
    }

    /**
     * 测试时间显示
     */
    @UiThread
    void setText2(){
        if(hour2>=0&&hour2<=9){
            hour_str2 = "0"+hour2;
        }else{
            hour_str2 = ""+hour2;
        }

        if(min2>=0&&min2<=9){
            min_str2 = "0" + min2;
        }else{
            min_str2 = min2+"";
        }

        if(sec2>=0&&sec2<=9){
            sec_str2 = "0"+sec2;
        }else{
            sec_str2 = sec2+"";
        }

        time_tv2.setText(hour_str2+":"+min_str2+":"+sec_str2);
    }

    @Extra("")
    String ftype;
    @Extra("")
    String gtype;

    /**
     * 每隔三十秒发送通知
     */
    @UiThread
    void sendTime(){
        HashMap<String,String> map = new HashMap<>();
        map.put("type","sync");
        map.put("idx",gtype);
        Futil.AddHashMap(map);
        new GetJSONObjectPostUtil(Url.EXAM, map, new GetJsonListener() {
            @Override
            public void onSuccessed(JSONObject result) {
//                try {
//
//                    showMessage(result.getString("return_data"));
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
            }

            @Override
            public void onFailed(HttpException error, String msg) {
                flag = false;
            }
        });
    }




    @UiThread
    void getfinish(){
        finish();
    }

    @UiThread
    void jiaojuan(){
        AnswerSucessActivity_.intent(context).extra("item",item).extra("idx",idx).startForResult(3);
        finish();
    }

    /**
     * 剩余交卷时间
     */
    @ViewById(R.id.commit_time_ll)
    LinearLayout commit_time_ll;

    /**
     * 时间显示布局
     */
    @ViewById(R.id.rel_time)
    RelativeLayout rel_time;

    /**
     * 参考答案
     */
    @ViewById(R.id.resolve_tv1)
    TextView resolve_tv1;

    /**
     * 解析答案
     */
    @ViewById(R.id.resolve_tv2)
    TextView resolve_tv2;

    /**
     * 答案布局
     */
    @ViewById(R.id.resolve_ll)
    LinearLayout resolve_ll;

    @ViewById(R.id.change_img)
    ImageView change_img;



    /**
     * 适配题型和改变当前题型
     */
    @UiThread
    void setAdatper(){
//        resolve_tv1.setText("正确答案: "+item.getTestItems().get(position).getAnswer()+"\t\t您的答案: "+item.getTestItems().get(position).getMe_answer());
//        resolve_tv2.setText("教材页码: "+item.getTestItems().get(position).getBook_page()+"\n题目解析: "+item.getTestItems().get(position).getExplain());
//        if(item.getTestItems().get(position).getAnswer().equals(item.getTestItems().get(position).getMe_answer())){
//            change_img.setImageResource(R.mipmap.iocn_2x21);
//        }else{
//            change_img.setImageResource(R.mipmap.iocn_2x22);
//        }

        if(item.getTestItems().get(position).getIs_explain()==0){
            resolve_ll.setVisibility(View.GONE);
            grading_img.setImageResource(R.mipmap.iocn_2x27);
            grading_tv_tv.setTextColor(getResources().getColor(R.color.content));
        }else{
            resolve_ll.setVisibility(View.VISIBLE);
            grading_img.setImageResource(R.mipmap.iocn_2x27pre);
            grading_tv_tv.setTextColor(getResources().getColor(R.color.app));
        }

        adatper = new AnswerAdatper(item.getTestItems().get(position).getAnswerItems(),item,position,context);
        listView.setAdapter(adatper);
        SetViewHeight.setListViewHeightBasedOnChildren(listView);
        adatper.notifyDataSetChanged();
        if(item.getTestItems().get(position).getIs_label().equals("1")){//标记
            label_img_press.setVisibility(View.VISIBLE);
            label_img.setVisibility(View.GONE);
            label_tv.setTextColor(getResources().getColor(R.color.app));
        }else{//非标记
            label_img_press.setVisibility(View.GONE);
            label_img.setVisibility(View.VISIBLE);
            label_tv.setTextColor(getResources().getColor(R.color.content));
        }
        title_answer.setText(item.getTestItems().get(position).getTitle());
        type_tv.setText(item.getTestItems().get(position).getType());



        if(next.getVisibility()==View.GONE){
            next.setVisibility(View.VISIBLE);
        }
        next.setText(position+1+"/"+item.getTestItems().size());
    }

    /**
     * 批阅
     */
    @ViewById(R.id.grading_tv_tv)
    TextView grading_tv_tv;

    /**
     * 批阅图标
     */
    @ViewById(R.id.grading_img)
    ImageView grading_img;


    @ViewById(R.id.next)
    TextView next;

    @ViewById(R.id.label_tv)
    TextView label_tv;

    @ViewById(R.id.label_img_press)
    ImageView label_img_press;

    @ViewById(R.id.label_img)
    ImageView label_img;

    @ViewById(R.id.title)
    TextView title;

    @ViewById(R.id.type_tv)
    TextView type_tv;

    @ViewById(R.id.title_answer)
    TextView title_answer;

    private Context context = this;
    private int position = 0;

    private AnswerAdatper adatper;

    @ViewById(R.id.listView)
    MyListView listView;

    /**
     * 标注
     */
    @Click(R.id.label_ll)
    void setLabel_ll(){
        if(label_img.getVisibility()==View.VISIBLE){
            HashMap<String,String> map = new HashMap<>();
            map.put("type","label");
            map.put("idx",item.getTestItems().get(position).getIdx());
            Futil.xutils(Url.EXAM,map,handler,Command.HANDLECODE12,context );
        }else{
            HashMap<String,String> map = new HashMap<>();
            map.put("type","unlabel");
            map.put("idx",item.getTestItems().get(position).getIdx());
            Futil.xutils(Url.EXAM,map,handler,Command.HANDLECODE13,context );
        }

    }

    /**
     * 上一题
     */
    @Click(R.id.last_tv)
    void last_tv(){
        if(position==0){
            showMessage("当前已是第一题");
            return;
        }
        --position;
        setAdatper();

    }

    /**
     * 下一题
     */
    @Click(R.id.next_tv)
    void next_tv(){
        /**
         * 根据题的类型决定是否作答
         */
//        if(item.getTestItems().get(position).getType().equals("单选题")||item.getTestItems().get(position).getType().equals("判断题")){
//            if(item.getTestItems().get(position).getMe_answer()==null){
//                showMessage("请选择答案");
//                return;
//            }
//        }else{
//            if(item.getTestItems().get(position).getMe_more_answer()==null||item.getTestItems().get(position).getMe_more_answer().size()==0){
//                showMessage("请选择答案");
//                return;
//            }
//        }


        if(position==item.getTestItems().size()-1){
            showMessage("当前是最后一题");
            return;
        }
        ++position;
        setAdatper();

    }

    /**
     * 选题
     */
    @Click(R.id.changetitle_lly)
    void changetitle_lly(){
        ChangeTitleActivity_.intent(this).extra("item",item).extra("type",type).startForResult(1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1&&resultCode==2){//选题

            position = data.getIntExtra("position",0);
            setAdatper();

        }else if(requestCode==3&&resultCode==4){//交卷
            position = data.getIntExtra("position",0);
            setAdatper();
        }
        flag = true;
        setTime();
    }




    /**
     * 批阅
     */
    @Click(R.id.grading_tv)
    void grading_tv(){
        if(type==Command.SUITE[1]){//测试才有交卷

            showConfirmDialog("是否提交问卷?",new OnDialogConfirmListener(){
                @Override
                public void onDialogConfirm() {
                    AnswerSucessActivity_.intent(context).extra("item",item).extra("idx",idx).startForResult(3);
                    if(SuiteActivity_.getActivity()!=null&&!SuiteActivity_.getActivity().isFinishing()){
                        SuiteActivity_.getActivity().finish();
                    }
                    finish();

                }
            });

        }else{//其他为批阅状态
            resolve_tv1.setText("正确答案: "+item.getTestItems().get(position).getAnswer());
            resolve_tv2.setText("教材页码: "+item.getTestItems().get(position).getBook_page()+"\n题目解析: "+item.getTestItems().get(position).getExplain());
            if(item.getTestItems().get(position).getMe_answer()!=null){
                if(item.getTestItems().get(position).getType().equals("单选题")||item.getTestItems().get(position).getType().equals("判断题")){
                    if(Command.ANSWER[Integer.parseInt(item.getTestItems().get(position).getMe_answer())].equals(item.getTestItems().get(position).getAnswer())){
                        change_img.setImageResource(R.mipmap.iocn_2x21);
                    }else{
                        change_img.setImageResource(R.mipmap.iocn_2x22);
                    }
                }
            }else if(item.getTestItems().get(position).getMe_more_answer()!=null){
                if(!item.getTestItems().get(position).getType().equals("单选题")||!item.getTestItems().get(position).getType().equals("判断题")) {
                    if (item.getTestItems().get(position).getMe_more_answer() != null && item.getTestItems().get(position).getMe_more_answer().size() != 0) {
                        String xn = "";
                        for (int i = 0; i < item.getTestItems().get(position).getMe_more_answer().size(); i++) {
                            xn += Command.ANSWER[Integer.parseInt(item.getTestItems().get(position).getMe_more_answer().get(i))];
                        }
                        if (xn.equals(item.getTestItems().get(position).getAnswer())) {
                            change_img.setImageResource(R.mipmap.iocn_2x21);
                        } else {
                            change_img.setImageResource(R.mipmap.iocn_2x22);
                        }
                    } else {
                        change_img.setImageResource(R.mipmap.iocn_2x22);
                    }
                }
            }
            else{
                change_img.setImageResource(R.mipmap.iocn_2x22);
            }


            if(resolve_ll.getVisibility()==View.VISIBLE){//取消状态
                resolve_ll.setVisibility(View.GONE);
                item.getTestItems().get(position).setIs_explain(0);
                grading_img.setImageResource(R.mipmap.iocn_2x27);
                grading_tv_tv.setTextColor(getResources().getColor(R.color.content));
            }else{//标注状态
                resolve_ll.setVisibility(View.VISIBLE);
                item.getTestItems().get(position).setIs_explain(1);
                grading_img.setImageResource(R.mipmap.iocn_2x27pre);
                grading_tv_tv.setTextColor(getResources().getColor(R.color.app));
            }

        }

    }

    /**
     * 返回
     */
    @Click(R.id.back)
    void back(){
        showConfirmDialog("是否退出答题?",new OnDialogConfirmListener(){
            @Override
            public void onDialogConfirm() {
                finish();
            }
        });
    }

    @Extra("")
    String idx;

    @Extra()
    int type;

    /**
     * 是否为真题
     */
    @Extra
    int is_true;

    @AfterViews
    void init(){
        title.setText(Command.SUITE_TYPE[type]);

        showLoading();
        HashMap<String,String> map = new HashMap<>();
        if(is_true==1){//真题
            map.put("type",Command.SUITE_TRUE_SEND[type]);
        }else if(is_true==2){//押题
            map.put("type",Command.SUITE_YA_SEND[type]);
        }else{//获取试题
            map.put("type",Command.SUITE_SEND[type]);
        }
        map.put("idx",idx);
        Futil.xutils(Url.EXAM,map,handler, Command.HANDLECODE11,context);
    }

    /**
     * 是否退出程序
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(KeyEvent.KEYCODE_BACK==keyCode){

            showConfirmDialog("是否退出答题?",new OnDialogConfirmListener(){
                @Override
                public void onDialogConfirm() {
                    finish();

                }
            });


        }



        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        flag = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!CommonUtils.isNetworkAvailable(this)){
            flag = false;
        }

        if(flag == false){
            flag = true;
            setTime();

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        flag = false;
    }




}
